package com.shujia.spark.core

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

import scala.util.Random

object Demo18PI {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setAppName("PI").setMaster("local[8]")
    val sc = new SparkContext(conf)

    val N = 10000000

    //构建一个长度为N的集合
    //    val list = 1 to N
    //含头不含尾
    val list = 0 until N

    val linesRDD: RDD[Int] = sc.parallelize(list)

    //随机生成点
    val dianRDD: RDD[(Double, Double)] = linesRDD.map(x => {

      //随机生成x轴和y轴  （-1 ， 1）
      val x = Random.nextDouble() * 2 - 1
      val y = Random.nextDouble() * 2 - 1
      (x, y)
    })

    //判断点在圆内还是在圆外
    val yuanDianRDD = dianRDD.filter(d => {
      val x = d._1
      val y = d._2

      //判断点到圆心的距离
      x * x + y * y <= 1
    })

    //计算Pi
    val PI = yuanDianRDD.count() / N.toDouble * 4

    println(PI)

  }

}
